// import crypto from 'crypto'
// import jsSha from 'js-sha256'
// import base64 from 'js-base64'
// import sha1 from 'sha1'
import rsa from 'jsencrypt';

import des from 'crypto-js';
import servicesApi from '@/services/servicesApi';
/** 
 * @description: DES对称加密
 * @param {*} message 需要加密的字符串，对象加密需要转成json字符串
 * @param {*} key 密钥（加密解密密钥同一个）
 * @return {*}
 */
export const desEncryptCrtpto = (message, key = 'xxxxxxxxxxxxxxxxxxxxx') => {
    const keyHex = des.enc.Utf8.parse(key)
    const option = { mode: des.mode.ECB, padding: des.pad.Pkcs7 }
    const encrypted = des.DES.encrypt(message, keyHex, option)
    let data = encrypted.ciphertext.toString() // 返回hex格式密文，如需返回base64格式：encrypted.toString()
    return data
}

/** 
 * @description:  DES对称解密
 * @param {*} message 需要解密的字符串，
 * @param {*} key 密钥（加密解密密钥同一个）
 * @return {*}
 */
export const desDecodeCrtpto = (message, key = 'xxxxxxxxxxxxxxxxxxxxx') => {
    const keyHex = des.enc.Utf8.parse(key)
    const decrypted = des.DES.decrypt(
        {
            ciphertext: des.enc.Hex.parse(message)
        }, // 若message是base64格式，则无需转16进制hex，直接传入message即可
        keyHex,
        {
            mode: des.mode.ECB,
            padding: des.pad.Pkcs7
        }
    )
    let data = decrypted.toString(des.enc.Utf8)
    return data
}

//md5
/** 
 * @description: MD5加密
 * @param {*} pwd 
 * @return {*}
 */
export const mdCrtpto = (pwd) => {
    let md5 = crypto.createHash('md5');
    md5.update(pwd);
    return md5.digest('hex');
}

// sha256
export const shaCrypto = (pwd) => {
    return jsSha.sha256(pwd);
}

//Base64
export const baseCrypto = (pwd) => {
    return base64.Base64.encode(pwd);
}


//sha1
export const sha1Crypto = (params) => {
    return sha1(params);
}

import { PUBLICKEY } from '@/store/storage'
//rea 非对称加密, 后端生成公秘钥,前端使用公秘钥加密,后端使用私密钥解密
export const rsaCrypto = (str) => {
    //实例化rsa
    let jse = new rsa();
    //加密公钥（由服务端生成）
    let pubKey = sessionStorage.getItem(PUBLICKEY)
    // console.log('session公钥为：%s', pubKey)
    jse.setPublicKey(pubKey);
    
    let data = jse.encrypt(str.toString());  // 进行加密
    // console.log('%s RSA加密为： %s', str.toString(), data)
    return data;
}